import React, { useState, useEffect, useRef } from 'react';
import { Tooltip, Input, InputNumber, Radio, Select, Row, Col } from 'antd';
import FormItem from '../../../../../components/FormItem';
import Modal from '../../../../../components/Modal';
import { ISRATELIMIT_OPTIONS, FEE_TYPE } from '../../../../../utils/constant';
import TypeManage from '../../../components/typeManage';
import { IconFont } from '../../../../../components/IconFont';
import services from '../../../../../services/api';
import FeeType from '../../../components/feeType';

export default function Base(props) {
  const { form, value, getPriceJson, dataSourceType } = props;
  const { getFieldValue, setFieldsValue } = form;
  const [dataSourceTypeOptions, setDataSourceTypeOptions] = useState([]);
  const priceJsonRef = useRef(null);

  useEffect(() => {
    getDataSourceTypeOptions();
  }, []);

  useEffect(() => {
    if (value.isRateLimit !== undefined) {
      setFieldsValue({ isRateLimit: value.isRateLimit });
    }
  }, [value.isRateLimit]);

  // 获取接口分组
  const getDataSourceTypeOptions = async () => {
    const { data, code } = await services.dataSourceType.list('_i');
    if (!code) setDataSourceTypeOptions(data);
  };

  // 接口分组
  const handleDataSourceType = () => {
    Modal.open({
      title: '接口分组管理',
      width: '800px',
      content: <TypeManage interfaceType='_i' onChange={(value) => handleChangeDataSourceTypeOptions(value)} />,
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  };

  const handleChangeDataSourceTypeOptions = (value) => {
    setDataSourceTypeOptions(value)
    const groupId = form.getFieldValue('groupId')
    if (!value.find(item => ('' + item.code) === ('' + groupId))) form.setFieldsValue({ groupId: undefined })
  }

  const hanleFeetypeChange = () => {
    getPriceJson(JSON.stringify({}));
  };

  // 计费类型
  const hanleFeetypeSet = () => {
    const feeType = getFieldValue('feeType');
    Modal.open({
      title: '计费类型配置',
      width: '800px',
      content: <FeeType feeType={feeType} value={value.priceJson} ref={priceJsonRef} />,
      maskClosable: false,
      ok: () => {
        const priceJson = priceJsonRef.current.getData();
        getPriceJson(JSON.stringify(priceJson));
        Modal.close();
      },
    });
  };

  const getFormItems = () => {
    const { name, flag, isRateLimit, rateMax = 0, groupId, desc, feeType } = value;
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '接口名称',
          ...layout,
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [
            { required: true, message: '请输入接口名称' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
          ],
        },
        component: <Input placeholder='请填写接口名称' />,
      },
      {
        label: {
          label: '接口标识',
          ...layout,
        },
        name: 'flag',
        options: {
          initialValue: flag,
          rules: [
            {
              required: true,
              message: '请输入接口标识',
            },
            {
              max: 50,
              message: '最长50个字符',
            },
            {
              pattern: /^[0-9a-zA-Z_]{1,}$/,
              message: '只能输入英文、数字、下划线',
            },
          ],
        },
        component: <Input placeholder='请填写接口标识' />,
      },
      {
        label: {
          label: '接口分组',
          ...layout,
        },
        name: 'groupId',
        options: {
          initialValue: groupId ? '' + groupId : undefined,
          rules: [
            {
              required: true,
              message: '请选择接口分组',
            },
          ],
        },
        component: (
          <Select placeholder='请选择接口分组'>
            {dataSourceTypeOptions.map((item) => (
              <Select.Option value={item.code} key={item.code}>
                {item.name}
              </Select.Option>
            ))}
          </Select>
        ),
        after: (
          <Tooltip title='管理分组'>
            <IconFont
              type='iconxitongshezhi'
              style={{
                fontSize: '16px',
                color: '#777',
              }}
              onClick={handleDataSourceType}
            />
          </Tooltip>
        ),
      },
      {
        label: {
          label: '限流',
          ...layout,
        },
        name: 'isRateLimit',
        options: {
          initialValue: isRateLimit || 0,
          rules: [
            {
              required: true,
              message: '请选择是否限流',
            },
          ],
        },
        component: (
          <Radio.Group>
            {ISRATELIMIT_OPTIONS.map((item, index) => (
              <Radio key={item} value={index}>
                {item}
              </Radio>
            ))}
          </Radio.Group>
        ),
      },
      ((getFieldValue('isRateLimit') === undefined && isRateLimit) || getFieldValue('isRateLimit')) && {
        label: {
          label: '流量',
          ...layout,
        },
        name: 'rateMax',
        options: {
          initialValue: rateMax,
          rules: [
            {
              required: true,
              message: '请输入流量',
            },
          ],
        },
        component: (
          <InputNumber
            min={0}
            max={9999}
            style={{ width: '100%' }}
            formatter={(value) => `${value}次/分`}
            precision={0}
            // parser={(value) => value.replace('次/分', '')}
          />
        ),
      },
      dataSourceType !== 1 && {
        label: {
          label: '计费方式',
          ...layout,
        },
        name: 'feeType',
        options: {
          initialValue: feeType,
          rules: [
            {
              required: true,
              message: '请选择计费方式',
            },
          ],
        },
        component: (
          <Select placeholder='请选择计费方式' onChange={hanleFeetypeChange}>
            {FEE_TYPE.map((item, index) => (
              <Select.Option value={index} key={item}>
                {item}
              </Select.Option>
            ))}
          </Select>
        ),
        after: ((getFieldValue('feeType') === undefined && !!feeType) || !!getFieldValue('feeType')) && (
          <Tooltip title='配置计费规则'>
            <IconFont
              type='iconxitongshezhi'
              style={{
                fontSize: '16px',
                color: '#777',
              }}
              onClick={() => hanleFeetypeSet()}
            />
          </Tooltip>
        ),
      },
      {
        label: {
          label: '数据源描述',
          ...layout,
        },
        name: 'desc',
        options: {
          initialValue: desc,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: <Input.TextArea placeholder='请输入' />,
      },
    ].filter(Boolean);
  };

  return (
    <Row type='flex' gutter={20}>
      {getFormItems().map((item) => {
        return (
          <Col span={8} key={item.name}>
            <FormItem form={form} item={item} colNum={1} />
          </Col>
        );
      })}
    </Row>
  );
}
